package bookstore.utils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Base64;

public class CryptoUtils {
    public byte[] encrypt(Long uid, byte[] pass) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            SecretKey sk = new SecretKeySpec(md5.digest(uid.toString().getBytes()), "HmacSHA256");

            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(sk);
            mac.update(pass);
            return mac.doFinal();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean check(Long uid, byte[] pass, byte[] pwd) {
        byte[] enc = encrypt(uid, pass);

        Base64.Encoder encoder = Base64.getEncoder();
        String e1 = encoder.encodeToString(pwd);
        String e2 = encoder.encodeToString(enc);

        return e1.equals(e2);
    }
}
